package channel

import (
	"fmt"
	"sync"
)

/*
type Worker struct {
	id int
	in chan int
	done chan bool
}

func doWork(w Worker){
	for {
		fmt.Printf("worker %d receive %c\n",w.id,<-w.in)
		w.done<-true
	}
}

func createWorker(id int) Worker{
	worker := Worker{
		id: id,
		in: make(chan int),
		done: make(chan bool),
	}
	go doWork(worker)
	return worker
}

func ChannelDemoDone(){
	var workers [10]Worker
	for i:=0;i<10;i++{
		workers[i] = createWorker(i)
	}

	go func(){
		for i:=0;i<10;i++{
			workers[i].in<- 'a'+i
		}
	}()
	for _,tempWorker := range workers{
		<-tempWorker.done
	}
}
*/

type Worker struct {
	id int
	in chan int
	wg *sync.WaitGroup
}

func doWork(w Worker) {
	for n := range w.in {
		fmt.Printf("worker %d receive %c\n", w.id, n)
		w.wg.Done()
	}
}

func createWorker(id int, wg *sync.WaitGroup) Worker {
	worker := Worker{
		id: id,
		in: make(chan int),
		wg: wg,
	}
	go doWork(worker)
	return worker
}

func ChannelDemoDone() {
	var wg sync.WaitGroup
	var workers [10]Worker
	for i := 0; i < 10; i++ {
		workers[i] = createWorker(i, &wg)
	}

	wg.Add(10)

	for i := 0; i < 10; i++ {
		workers[i].in <- 'a' + i
	}

	wg.Wait()
}
